package git.soulbgm.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.export.styler.ExcelExportStylerBorderImpl;
import git.soulbgm.common.Base64DecodedMultipartFile;
import git.soulbgm.pojo.User;
import git.soulbgm.utils.EasyPoiUtil;
import git.soulbgm.utils.PoiCommon;
import org.apache.poi.util.IOUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;

/**
 * @author SoulBGM
 * @version 1.0
 * @date 2019/7/23 19:27
 */
@RestController
public class UserController {

    @RequestMapping("excelExport")
    public String excelExport(HttpServletResponse response) {
        List<User> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            User u = new User();
            u.setId(i + 1);
            u.setUsername("Username" + i);
            u.setAge(i * 4);
            u.setBirthDate(new Date());
            list.add(u);
        }
        PoiCommon.setResponse(response, "user_test");
        try {
            EasyPoiUtil.modelWriterExcel(response.getOutputStream(), list, User.class, ExcelExportStylerBorderImpl.class, null);
            return "success";
        } catch (IOException e) {
            e.printStackTrace();
            return "error";
        }
    }

    @RequestMapping(path = "importExcel", method = RequestMethod.POST)
    public String importExcel(HttpServletRequest request) throws Exception {
        MultipartFile multipartFile = getMultipartFile(request, "file");
        if (multipartFile != null) {
            ImportParams params = new ImportParams();
            params.setTitleRows(1);
            params.setHeadRows(1);
            List<User> list = ExcelImportUtil.importExcel(multipartFile.getInputStream(), User.class, params);
            System.out.println(list);
            System.out.println(list.size());
            return "success";
        }
        return "error";
    }

    @RequestMapping(path = "getFileBase64", method = RequestMethod.POST)
    public String getFileBase64(HttpServletRequest request) throws IOException {
        MultipartFile multipartFile = getMultipartFile(request, "file");
        byte[] data = IOUtils.toByteArray(multipartFile.getInputStream());
        return "data:" + multipartFile.getContentType() + ";base64," + DatatypeConverter.printBase64Binary(data);
    }

    @RequestMapping(path = "base64WordExport", method = RequestMethod.POST)
    public String base64WordExport(HttpServletResponse response, @RequestBody String base64) throws Exception {
        MultipartFile multipartFile = getBase64MultipartFile(base64);
        return downloadOneImageWord(response, multipartFile);
    }

    @RequestMapping(path = "wordExport", method = RequestMethod.POST)
    public String wordExport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartFile multipartFile = getMultipartFile(request, "file");
        return downloadOneImageWord(response, multipartFile);
    }

    @RequestMapping(path = "wordMultipleSheetsImageExport", method = RequestMethod.POST)
    public String wordMultipleSheetsImageExport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartFile multipartFile = getMultipartFile(request, "file");
        return downloadMultipleSheetsImageWord(response, multipartFile);
    }

    @RequestMapping(path = "wordMultipleGroupImageExport", method = RequestMethod.POST)
    public String wordMultipleGroupImageExport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartFile multipartFile = getMultipartFile(request, "file");
        return downloadMultipleGroupImageWord(response, multipartFile);
    }

    /**
     * 下载一个图片的word
     *
     * @param response      HttpServletResponse对象
     * @param multipartFile 文件对象
     * @return success
     */
    public String downloadOneImageWord(HttpServletResponse response, MultipartFile multipartFile) throws Exception {
        Map<String, Object> map = getDataMap(multipartFile);

        PoiCommon.setResponse(response, "test_word.docx");
        EasyPoiUtil.templateWriterWord(response.getOutputStream(), map, "word/Image1.docx");
        return "success";
    }

    /**
     * 下载多张图片的word
     *
     * @param response      HttpServletResponse对象
     * @param multipartFile 文件对象
     * @return success
     */
    public String downloadMultipleSheetsImageWord(HttpServletResponse response, MultipartFile multipartFile) throws Exception {
        Map<String, Object> map = getDataMap(multipartFile);

        List<ImageEntity> imageList = new ArrayList<>(10);
        File file = new File("G:\\meizitu\\page12");
        File[] files = file.listFiles();
        for (File f : files) {
            ImageEntity img = new ImageEntity(f.getAbsolutePath(), 600, 854);
            imageList.add(img);
        }
        PoiCommon.setResponse(response, "test_word.docx");
        EasyPoiUtil.templateWriterWordImage(response.getOutputStream(), map, "word/Image2.docx", imageList);
        return "success";
    }

    /**
     * 下载多组图片的word 每组图片都有多张
     *
     * @param response      HttpServletResponse对象
     * @param multipartFile 文件对象
     * @return success
     */
    public String downloadMultipleGroupImageWord(HttpServletResponse response, MultipartFile multipartFile) throws Exception {
        Map<String, Object> map = getDataMap(multipartFile);

        Map<String, List<ImageEntity>> multiplePictures = new HashMap<>(3);
        for (int i = 1; i <= 3; i++) {
            List<ImageEntity> imageList = new ArrayList<>(10);
            File file = new File("G:\\meizitu\\page" + i);
            File[] files = file.listFiles();
            for (File f : files) {
                ImageEntity img = new ImageEntity(f.getAbsolutePath(), 600, 854);
                imageList.add(img);
            }
            multiplePictures.put("page" + i, imageList);
        }
        PoiCommon.setResponse(response, "test_word.docx");
        EasyPoiUtil.templateWriterWordImage(response.getOutputStream(), map, "word/Image3.docx", multiplePictures);
        return "success";
    }

    public Map<String, Object> getDataMap(MultipartFile multipartFile) throws IOException {
        BufferedImage bufferedImage = ImageIO.read(multipartFile.getInputStream());
        byte[] data = IOUtils.toByteArray(multipartFile.getInputStream());
        ImageEntity image = new ImageEntity();
        image.setHeight(bufferedImage.getHeight());
        image.setWidth(bufferedImage.getWidth());
        image.setData(data);
        image.setType(ImageEntity.Data);

        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("department", "Easypoi");
        map.put("name", "SoulBGM");
        map.put("time", format.format(new Date()));
        map.put("testCode", image);
        return map;
    }


    private MultipartFile getMultipartFile(HttpServletRequest request, String paramName) {
        if (paramName == null) {
            return null;
        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        return multipartRequest.getFile(paramName);
    }

    public MultipartFile getBase64MultipartFile(String imgStr) {
        try {
            String[] baseStr = imgStr.split(",");
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            b = base64Decoder.decodeBuffer(baseStr[1]);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new Base64DecodedMultipartFile(b, baseStr[0]);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
